<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊天室</title>
    <style>
        #chatroom{
            height: 500px;
            width: 460px;
            border: 2px solid slateblue;
            border-radius: 10px;
            padding: 10px;
            overflow: auto;
            margin-bottom: 20px;
        }
    </style>
    <%- include conmon %>
</head>
<body>
    <!-- 头部结构 -->
    <%- include('header',{title:"chat"}) %>
    <div>
        <h2>Socket聊天室</h2>
        <div id="chatroom">
            <!-- 接收聊天内容 -->
        </div>
        <div>
            <input type="text" placeholder="请输入聊天内容" id="word">
            <input type="button" id="sendbtn" value="发送消息">
        </div>
    </div>
    <!-- 尾部结构 -->
    <%- include('footer',{title:"公用尾部结构"}) %>
    <script>
        // 1.创建客户端socket
        const ws = new WebSocket("ws://localhost:3900");  //ws协议

        // 2.连接服务器的socket
        ws.onopen = function(){
            ws.send("我已经上线了。。。");
        }
        // 3.发消息给服务器
        function sendmsg(){
            ws.send(word.value); //id的唯一性
            word.value = '';
        }
        sendbtn.onclick = sendmsg;  //点击发送
        document.onkeydown = function(e){  //按键发送
            if(e.keyCode == 13){
                sendmsg();
            }
        }
        // 4.接收服务器发来的消息
        ws.onmessage = function(data){
            console.log(data);
            document.getElementById('chatroom').innerHTML += `<p>${data.data}</p>`;
        }

        // 5.监听服务器关闭或异常
        ws.onclose = function(){
            console.log(`服务器已经关闭`);
        }
        ws.onerror = function(err){
            console.log(`服务器异常: ${err}`);
        }

    </script>
</body>
</html>